package com.sgb.kjwl.view.ui.activity.leaseAsk;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;

import androidx.databinding.DataBindingUtil;

import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityAskLeasePriceBinding;
import com.sgb.kjwl.di.machine.DaggerMachineComponent;
import com.sgb.kjwl.di.machine.MachineModule;
import com.sgb.kjwl.model.entity.user.UnitEntity;
import com.sgb.kjwl.utils.EditInputFilter;
import com.sgb.kjwl.view.ui.activity.leaseAsk.publish.AskLeaseFarmActivity2;
import com.swgk.core.dialog.CommonDialog;
import com.swgk.core.dialog.RoundCornerDialog;
import com.sgb.kjwl.viewmodel.machine.AskLeaseQuePriceModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PickSelectEntity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

/**
 * 租赁-报价页面(一键报价)
 */
public class AskLeaseQuedPriceActivity extends AppActivity {

    @Inject
    AskLeaseQuePriceModel viewModel;

    private ActivityAskLeasePriceBinding binding;
    private String id = "";
    private String type = "";
    private List<PickSelectEntity<List<PickSelectEntity>>> unitList = new ArrayList<>();
    private String key = "";
    private String value = "";
    private String negotiable = "0";//是否面议 1：面议，0：非面议
    private String secondCategoryName = "";//二级分类名称
    private String countUnit = "";//计量单位
    private String timeUnit = "";// 租赁时长单位
    private String acreage = "";//面积
    private String brandNo = "";
    private String modelNo = "";
    private String brandName = "";//品牌名称
    private String modelName = "";// 出厂型号名称（或车系名称）
    private boolean isPriceUnit = false;//是否可随意选择价格单位
    private List<PickSelectEntity> priceMatchUnitDatas = new ArrayList<>();//辆/台 单位列表

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerMachineComponent.builder().appComponent(appComponent)
                .machineModule(new MachineModule(this))
                .build()
                .inject(this);
    }

    public static void start(Context context,
                             String id,
                             String type,
                             String quoteUtil,
                             String negotiable) {
        Intent intent = new Intent();
        intent.setClass(context, AskLeaseQuedPriceActivity.class);
        intent.putExtra("id", id);
        intent.putExtra("type", type);
        intent.putExtra("quoteUtil", quoteUtil);
        intent.putExtra("negotiable", negotiable);
        context.startActivity(intent);
    }

    public static void start(Context context,
                             String id,
                             String type,
                             String quoteUtil,
                             String negotiable,
                             String secondCategoryName,
                             String countUnit,
                             String timeUnit,
                             String acreage,
                             String brandNo,
                             String brandName,
                             String modelNo,
                             String modelName) {
        Intent intent = new Intent();
        intent.setClass(context, AskLeaseQuedPriceActivity.class);
        intent.putExtra("id", id);
        intent.putExtra("type", type);
        intent.putExtra("quoteUtil", quoteUtil);
        intent.putExtra("negotiable", negotiable);
        intent.putExtra("secondCategoryName", secondCategoryName);
        intent.putExtra("countUnit", countUnit);
        intent.putExtra("timeUnit", timeUnit);
        intent.putExtra("acreage", acreage);
        intent.putExtra("brandName", brandName);
        intent.putExtra("modelName", modelName);
        intent.putExtra("brandNo", brandNo);
        intent.putExtra("modelNo", modelNo);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_ask_lease_price);
        binding.include.ivBack.setOnClickListener(view -> onBackPressed());
        binding.include.titleView.setText("报价");
        binding.tvPrice.setFilters(new EditInputFilter[]{new EditInputFilter(99999999.99, 2)});
        binding.itvAcreage.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        binding.itvAcreage.setFilters(new EditInputFilter[]{new EditInputFilter(99999999.99, 1, 2)});
        binding.tvSubmit.setOnClickListener(v -> showDialogs());
        binding.itemTvUnit.setOnWholeItemClickListener(view -> showPriceMatchUnitPicker());
        binding.tvPriceUnit.setOnClickListener(v -> {
            if (isPriceUnit) {
                showPriceUnitPop();
            }
        });
    }

    @Override
    protected void init() {
        id = getIntent().getStringExtra("id");
        type = getIntent().getStringExtra("type");
        value = getIntent().getStringExtra("quoteUtil");
        negotiable = getIntent().getStringExtra("negotiable");
        secondCategoryName = getIntent().getStringExtra("secondCategoryName");
        countUnit = getIntent().getStringExtra("countUnit");
        timeUnit = getIntent().getStringExtra("timeUnit");
        acreage = getIntent().getStringExtra("acreage");
        brandName = getIntent().getStringExtra("brandName");
        modelName = getIntent().getStringExtra("modelName");
        brandNo = getIntent().getStringExtra("brandNo");
        modelNo = getIntent().getStringExtra("modelNo");
        isPriceUnit = "1".equals(negotiable);
        binding.ivPriceUnitArrow.setVisibility(isPriceUnit ? View.VISIBLE : View.GONE);
//        setDrawable(isPriceUnit);
        if (!TextUtils.isEmpty(timeUnit) && !isPriceUnit) {
            binding.tvPriceUnit.setText("元/" + timeUnit);
        }
        if (!TextUtils.isEmpty(countUnit)) {
            binding.itemTvUnit.setContent(countUnit);
            binding.itemTvUnit.setArrowVisible(false);
            binding.itemTvUnit.setOnWholeItemClickListener(null);
        }
        binding.itemTvType.setContent(secondCategoryName);
        binding.itvBrand.setContent(brandName);
        binding.itvModel.setContent(modelName);
        binding.itvAcreage.setContent(acreage);
        if ("0".equals(type)) {//机械
            binding.itemTvType.setLabelName("机械类型");
        } else if ("1".equals(type)) {//设备
            binding.itemTvType.setLabelName("设备类型");
        } else if ("2".equals(type)) {//车辆
            binding.itemTvType.setLabelName("车辆车型");
            binding.itvModel.setLabelName("车系");
            binding.itemTvUnit.setArrowVisible(false);
            binding.itemTvUnit.setOnWholeItemClickListener(null);
        } else if ("3".equals(type)) {//房产价格单位
            binding.itemTvType.setLabelName("房产类型");
            binding.itvBrand.setVisibility(View.GONE);
            binding.itvModel.setVisibility(View.GONE);
            binding.itvAcreage.setVisibility(View.VISIBLE);
            binding.itemTvUnit.setContent(TextUtils.isEmpty(countUnit) ? "m²" : countUnit);
            binding.itemTvUnit.setArrowVisible(false);
            binding.itemTvUnit.setOnWholeItemClickListener(null);
        } else if ("4".equals(type)) {//土地价格单位
            binding.itemTvType.setLabelName("土地类型");
            binding.itvBrand.setVisibility(View.GONE);
            binding.itvModel.setVisibility(View.GONE);
            binding.itvAcreage.setVisibility(View.VISIBLE);
            binding.itemTvUnit.setContent(TextUtils.isEmpty(countUnit) ? "m²" : countUnit);
            binding.itemTvUnit.setArrowVisible(false);
            binding.itemTvUnit.setOnWholeItemClickListener(null);
        } else if ("5".equals(type)) {//工厂价格单位
            binding.itemTvType.setLabelName("工厂类型");
            binding.itvBrand.setVisibility(View.GONE);
            binding.itvModel.setVisibility(View.GONE);
            binding.itvAcreage.setVisibility(View.VISIBLE);
            binding.itemTvUnit.setContent(TextUtils.isEmpty(countUnit) ? "m²" : countUnit);
            binding.itemTvUnit.setArrowVisible(false);
            binding.itemTvUnit.setOnWholeItemClickListener(null);
        } else if ("6".equals(type)) {//农机
            binding.itemTvType.setLabelName("农机类型");
        }
        viewModel.getLeaseTimeUnit(type);
        initData();
    }

    private void initData() {
        priceMatchUnitDatas = new ArrayList<>();
        priceMatchUnitDatas.add(new PickSelectEntity("0", "台"));
        priceMatchUnitDatas.add(new PickSelectEntity("1", "辆"));
    }

    private void toSubmit() {
        if (TextUtils.isEmpty(binding.tvPrice.getText())) {
            MToast.showToast(AskLeaseQuedPriceActivity.this, "请输入报价金额");
            return;
        }

        try {
            if (Double.parseDouble(binding.tvPrice.getText().toString().trim()) <= 0) {
                MToast.showToast(AskLeaseQuedPriceActivity.this, "报价金额最小为0.01");
                return;
            }
            if (binding.itvAcreage.getVisibility() == View.VISIBLE && Double.parseDouble(binding.itvAcreage.getContent().trim()) <= 0) {
                MToast.showToast(AskLeaseQuedPriceActivity.this, "面积最小为1");
                return;
            }
        } catch (Exception e) {

        }

        String remark = "";
        if (!TextUtils.isEmpty(binding.cfkEdit.getEditContent())) {
            remark = binding.cfkEdit.getEditContent();
        }

        Map map = new HashMap();
        map.put("brandName", binding.itvBrand.getContent());
        map.put("brandNo", brandNo);
        map.put("modelName", binding.itvModel.getContent());
        map.put("modelNo", modelNo);
        map.put("rentalSeekId", id);
        map.put("quotePrice", binding.tvPrice.getText().toString());
        map.put("remark", remark);//详细描述
        map.put("quoteUtil", binding.tvPriceUnit.getText().toString());//价格单位
        map.put("rentalCountUnit",binding.itemTvUnit.getContent());//计量单位
//        map.put("quoteKey", key);//价格单位id
        map.put("categoryType", type);//0机械，1设备 2车辆，3房产，4土地 5工厂 6农机
        map.put("rentalArea", binding.itvAcreage.getContent().trim());//面积
        viewModel.toSubmit(map);
    }

    //设置默认值
    public void doPriceUnit(List<PickSelectEntity<List<PickSelectEntity>>> list) {
        if (list == null || list.size() == 0) {
            binding.tvPriceUnit.setText("元/天");
            return;
        }
        this.unitList = getUnitList(list);
        if (TextUtils.isEmpty(binding.tvPriceUnit.getText())) {
            binding.tvPriceUnit.setText(unitList.get(0).getProjectscale());
        }
//        if (list != null && list.size() > 0) {
//            PickSelectEntity leaseCarPrice = getLeaseCarPriceByValue(list, value);
//            if (leaseCarPrice == null) {
//                if (TextUtils.isEmpty(value)) {
//                    leaseCarPrice = list.get(0);
//                    key = leaseCarPrice.getNo();
//                    value = "元/" + leaseCarPrice.getProjectscale();
//                }
//            } else {
//                key = leaseCarPrice.getNo();
//                value = "元/" + leaseCarPrice.getProjectscale();
//            }
//            binding.tvPriceUnit.setText(value);
//        }
    }

    private List<PickSelectEntity<List<PickSelectEntity>>> getUnitList(List<PickSelectEntity<List<PickSelectEntity>>> unitList) {
        for (PickSelectEntity entity : unitList) {
            entity.setProjectscale("元/" + entity.getProjectscale());
        }
        return unitList;
    }
//
//    /**
//     * 根据value 找出在list中的实体
//     *
//     * @param unitList
//     * @param v
//     * @return
//     */
//    private PickSelectEntity getLeaseCarPriceByValue(List<PickSelectEntity> unitList, String v) {
//        PickSelectEntity carPrice;
//        for (int i = 0; i < unitList.size(); i++) {
//            carPrice = unitList.get(i);
//            if (carPrice.getProjectscale().equals(v)) {
//                return carPrice;
//            }
//        }
//        return null;
//    }

    /**
     * 弹出报价单位
     */
    private void showPriceUnitPop() {
        hideKeyboard();
        if (unitList != null && unitList.size() > 0) {
            OptionsPickerView businessOption = new OptionsPickerBuilder(AskLeaseQuedPriceActivity.this, (options1, options2, options3, v) -> {
                key = unitList.get(options1).getNo();
                value = unitList.get(options1).getProjectscale();
                binding.tvPriceUnit.setText(value);
            }).build();
            businessOption.setPicker(unitList);
            businessOption.setSelectOptions(0);
            businessOption.setTitleText("选择单位");
            businessOption.show();
        }
    }

    //数量单位（辆/台）
    private void showPriceMatchUnitPicker() {
        if (null != priceMatchUnitDatas && priceMatchUnitDatas.size() > 0) {
            OptionsPickerView businessOption = new OptionsPickerBuilder(AskLeaseQuedPriceActivity.this, (options1, options2, options3, v) -> {
                String content = priceMatchUnitDatas.get(options1).getProjectscale();
                binding.itemTvUnit.setContent(content);
            }).build();
            businessOption.setPicker(priceMatchUnitDatas);
            businessOption.setSelectOptions(1);
            businessOption.show();
        }
    }

    /**
     * 确认提交提示对话框
     */
    private void showDialogs() {
        View view = View.inflate(AskLeaseQuedPriceActivity.this, R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(AskLeaseQuedPriceActivity.this, 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失

        TextView tv_message = (TextView) view.findViewById(R.id.tv_message);
        TextView tv_title = view.findViewById(R.id.tv_title);
        TextView tv_logout_confirm = (TextView) view.findViewById(R.id.tv_logout_confirm);
        tv_title.setVisibility(View.VISIBLE);
        TextView tv_logout_cancel = (TextView) view.findViewById(R.id.tv_logout_cancel);
        tv_title.setText("提交报价");
        tv_message.setText("确认提交此报价?");
        //确定
        tv_logout_confirm.setOnClickListener(v -> {
            roundCornerDialog.dismiss();
            toSubmit();
        });
        //取消
        tv_logout_cancel.setOnClickListener(v -> roundCornerDialog.dismiss());
        roundCornerDialog.show();
    }

    //设置右侧箭头图片
    private void setDrawable(boolean b) {
        Drawable drawable = null;
        if (b) {
            drawable = getResources().getDrawable(R.mipmap.arrow_right);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        }
        binding.tvPriceUnit.setCompoundDrawables(null, null, drawable, null);
    }

    //隐藏软键盘
    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        // 隐藏软键盘
        imm.hideSoftInputFromWindow(this.getWindow().getDecorView().getWindowToken(), 0);
    }

    @Override
    public void onBackPressed() {
        initDialog();
        return;
    }

    public void initDialog() {
        new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                .setTitle("提示")
                .setMsg("确定要退出吗？退出后已填写的内容将不会保存！")
                .setDialogCallBack(new CommonDialog.DialogCallBack() {
                    @Override
                    public void onRightClick() {
                        AskLeaseQuedPriceActivity.this.finish();
                    }

                    @Override
                    public void onLeftClick() {
                        return;
                    }
                }).show();
    }
}
